$(document).ready(() => {

    const serverHost = 'http://10.222.29.198:8080/amc-c';

    let url = location.search;
    let result = url.split("=");
    let merchantId = result[1];

    window.sessionStorage.setItem('merchantId', merchantId)

    // request foodType list
    $.ajax({
        url: `${serverHost}/food/foodtypelist?merchantId=${merchantId}`,
        type: 'GET',
        success: data => {
            data.forEach((item, index) => {
                let typeName = item.typeName;
                let tId = item.typeId;
                let content = `<option value="${tId}+${merchantId}">${item.typeName}</option>`
                $("#classifyBtn").append(content);
            })
        },
        error: () => {
            console.log("fail");
        }
    });

    // request food List
    $.ajax({
        url: `${serverHost}/food/foodlist?merchantId=${result[1]}`,
        type: 'GET',
        success: data => {
            //            $('#merchantName').text(data[0].merchantName);
            data.forEach((item, index) => {
                let foodId = item.foodId;
                let foodName = item.foodName;
                let foodPrice = item.foodPrice;
                let foodPic = item.foodPic;
                //                let merchantName = item.merchantName;
                let content = ` <div class="menu-page-grids">
			                <div class="col-md-3 menu-grids-info">
			                    <img style="min-width: 250px; min-height: 260px;" src="${foodPic}" alt="" title="">
			                    <h4><a href="#">${foodName}</a></h4>
			                    <p>$${foodPrice}</p>
			                    <div class="opration">
			                        <a onclick=\"addShopBtn(\'${foodId}\')\">Add</a>
			                    </div>
			                </div>
                		</div>`
                if (index % 4 == 1 && index != 1) {
                    content = '<div class="menu-page-grids">' + content + '</div><div class="clearfix"></div>'
                }

                $('#content').append(content)
            })
        },
        error: () => {
            console.log("ERROR!!!!")
        }
    });

    // request comment list
    $.ajax({
        url: `${serverHost}/comment/commentlist?merchantId=${merchantId}`,
        type: 'GET',
        success: data => {
            console.log(data)
            let content = ``
            data.forEach(item => {

                let createTime = new Date();
                createTime.setTime(item.createTime * 1000);
                let createT = (createTime.toLocaleString()).split(' ')[1]

                if (item.commentReply == null) {
                    content += `<li>
                                <p style="text-align: left;">用户 <span style="color:cadetblue;">${item.customerName}:</span> </p>
                                <p style="text-align: left; font-size: 14px;">发表于: <span style="color: #9f9f9f;">${createT}</span></p>
                                <p style="text-align: left;">${item.commentText}</p>
                            </li><hr style="color:#fff;"/>`
                } else {
                    let replyTime = new Date();
                    replyTime.setTime(item.replyTime * 1000);
                    let replyT = (replyTime.toLocaleString()).split(' ')[1]

                    content += `<li>
                                <p style="text-align: left;">用户 <span style="color:cadetblue;">${item.customerName}:</span> </p>
                                <p style="text-align: left; font-size: 14px;">发表于: <span style="color: #9f9f9f;">${createT}</span></p>
                                <p style="text-align: left;">${item.commentText}</p>
                                <p style="text-align: right; color: coral;">商家</p>
                                <p style="text-align: right; font-size: 14px;">回复于: <span style="color: #9f9f9f;">${replyT}</span></p>
                                <p style="text-align: right; ">${item.commentReply}</p>
                            </li><hr style="color:#fff;"/>`
                }
            })

            $('#sidebarContent').html('<ul id="panel">' + content + '</ul>')
        },
        error: () => {
            console.log('Request Merchant CommentList Fail.')
        }
    })

    // Search
    $('#searchBtn').on('click', () => {
        let searchContent = $('#searchContent').val();
        console.log(searchContent);

        $.ajax({
            url: `${serverHost}/food/search?keyword=${searchContent}`,
            type: 'GET',
            success: data => {
                $('#content').html('');
                console.log("data: " + data)
                data.forEach((item, index) => {
                    console.log(item)
                    let foodId = item.foodId;
                    let foodName = item.foodName;
                    let foodPrice = item.foodPrice;
                    let foodPic = item.foodPic;
                    let content = `<div class="menu-page-grids">
		                	<div class="col-md-3 menu-grids-info">
			                    <img src="${foodPic}" alt="" title="">
			                    <h4><a href="#">${foodName}</a></h4>
			                    <p>$${foodPrice}</p>
			                    <div class="opration">
			                        <a href="#" onclick=\"addShopBtn(\'${foodId}\')\" >Add</a>
			                    </div>
			                </div>
	                	</div>`
                    if (index % 4 == 1 && index != 1) {
                        content = '<div class="menu-page-grids">' + content + '</div><div class="clearfix"></div>'
                    }

                    $('#content').append(content)
                })
            },

            error: () => {
                console.log('REQUEST ERROR')
            }
        })
    })

    // get merchant scope
    $.ajax({
        url: `${serverHost}/merchant/scope?merchantId=${merchantId}`,
        type: 'GET',
        success: data => {
            console.log(data)
            $('#merchant_scope').text(data.toFixed(1))
        },
        error: () => {
            console.log("fail");
        }
    })

    $("#flip").click(function () {
        $("#panel").slideToggle("slow");
    });

    let view = new ShopCartView('#shopcart');
    let model = new ShopCartModel([]);
    let component = new ShopCartComponent(model, view);
    window.view = view;
    window.model = model;
    window.component = component;

    // init comment list
    new SidebarView();
});

// 添加入购物车
function addShopBtn(foodId) {
    const serverHost = 'http://10.222.29.198:8080/amc-c';
    console.log('SHOP CAR FID: ' + foodId)
    $.ajax({
        url: `${serverHost}/shopcar/addfood?foodId=${foodId}`,
        type: 'GET',
        success: data => {
            console.log(data);
            // 获取数据成功
            component.bindAddFoodBtn(data.foodId, data.foodName, data.foodPrice, data.foodPic);
        },
        error: function () {
            console.log("REQUEST ERROR!!!")
        }
    })
}

function countAdd(fId) {
    console.log(fId)
    $.ajax({
        url: 'http://10.222.29.196:8080/AddShopCarServlet?fId=' + fId,
        type: 'GET',
        success: function (data) {
            console.log(data);
            let result = JSON.parse(data);
            window.localStorage.setItem("foods", data)
        },
        error: function () {
            console.log("REQUEST ERROR!!!")
        }
    })
}

function countSub(fId) {
    console.log(fId)
    $.ajax({
        url: 'http://10.222.29.196:8080/DeleteShopCarServlet?fId=' + fId,
        type: 'GET',
        success: function (data) {
            console.log(data);
            let result = JSON.parse(data);
            window.localStorage.setItem("foods", data)
        },
        error: function () {
            console.log("REQUEST ERROR!!!")
        }
    })
}

function classify(op) {
    let value = $(op).val().split('+');
    let tId = value[0]
    let mId = value[1]
    console.log(tId, mId)
    const serverHost = window.config.serverHost
    $.ajax({
        url: `${serverHost}/food/updatefoodlist?foodTypeId=${tId}&merchantId=${mId}`,
        type: 'GET',
        success: function (data) {
            $("#content").html("");
            data.forEach((item, index) => {
                console.log(item)
                let foodId = item.foodId;
                let foodName = item.foodName;
                let foodPrice = item.foodPrice;
                let foodPic = item.foodPic;
                let content = `<div class="menu-page-grids">
		                	<div class="col-md-3 menu-grids-info">
			                    <img src="${foodPic}" alt="" title="">
			                    <h4><a href="#">${foodName}</a></h4>
			                    <p>$${foodPrice}</p>
			                    <div class="opration">
			                        <a href="#" onclick=\"addShopBtn(\'${foodId}\')\" >Add</a>
			                    </div>
			                </div>
	                	</div>`
                if (index % 4 == 1 && index != 1) {
                    content = '<div class="menu-page-grids">' + content + '</div><div class="clearfix"></div>'
                }

                $('#content').append(content)
            })
        }
    });
};